package com.csun.dsms.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.csun.dsms.comment.core.utils.wrapper.WrapMapper;
import com.csun.dsms.comment.core.utils.wrapper.Wrapper;
import com.csun.dsms.mapper.DepartmentInfoMapper;
import com.csun.dsms.mapper.FileInfoMapper;
import com.csun.dsms.mapper.LearnInfoMapper;
import com.csun.dsms.model.process.DepartmentInfo;
import com.csun.dsms.model.process.FileInfo;
import com.csun.dsms.model.process.LearnInfo;
import com.csun.dsms.service.LearnInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class LearnInfoServiceImpl implements LearnInfoService {

    @Resource
    private LearnInfoMapper learnInfoMapper;

    @Resource
    private DepartmentInfoMapper departmentInfoMapper;

    @Autowired
    private FileInfoMapper fileInfoMapper;

    @Override
    public Wrapper<Object> addLearnInfo(LearnInfo learnInfo) {
        try {
            String department = learnInfo.getDepartment();
            BigInteger annexId = learnInfo.getAnnexId();
            String userName = learnInfo.getUserName();
            if (StrUtil.isBlank(department)) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "部门不能为空");
            }
            if (annexId==null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "附件id不能为空");
            }
            if (StrUtil.isBlank(userName)){
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "学习人不能为空");
            }
            FileInfo fileInfo = fileInfoMapper.selectByPrimaryKey(annexId);
            if (fileInfo == null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "附件不存在");
            }
            if (StrUtil.isNotBlank(department)) {
                DepartmentInfo queryDepartmentInfo = new DepartmentInfo();
                queryDepartmentInfo.setDepartmentName(department);
                List<DepartmentInfo> departmentInfoList = departmentInfoMapper.select(queryDepartmentInfo);
                if (CollectionUtil.isNotEmpty(departmentInfoList)) {
                    String areaName = departmentInfoList.get(0).getAreaName();
                    learnInfo.setArea(areaName);
                }
            }
            learnInfo.setAnnexName(fileInfo.getFileName());
            learnInfo.setStatus("1");
            learnInfo.setCreatedTime(new Date());
            learnInfoMapper.insert(learnInfo);
            return WrapMapper.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper<Object> updateLearnInfo(LearnInfo learnInfo) {
        try {
            Integer id = learnInfo.getId();
            if (id == null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "id不能为空");
            }
            learnInfoMapper.updateByPrimaryKeySelective(learnInfo);
            return WrapMapper.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper<Object> queryLearnInfoPage(JSONObject reqJson) {
        try {
            DecimalFormat df = new DecimalFormat("0.00%");
            Integer pageSize = reqJson.getInteger("pageSize");
            Integer pageNum = reqJson.getInteger("pageNum");
            String department = reqJson.getString("department");
            PageHelper.startPage(pageNum, pageSize);

            LearnInfo queryLearnInfo = new LearnInfo();
            queryLearnInfo.setStatus("1");
            queryLearnInfo.setDepartment(department);
            List<LearnInfo> learnInfoList = learnInfoMapper.select(queryLearnInfo);
            Collections.sort(learnInfoList, Comparator.comparing(LearnInfo::getId).reversed());
            return WrapMapper.ok(new PageInfo<>(learnInfoList));
        } catch (Exception e) {
            e.printStackTrace();
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper<Object> queryLearnInfoList(JSONObject reqJson) {
        try {
            DecimalFormat df = new DecimalFormat("0.00%");
            List<Object> resList = CollectionUtil.newArrayList();
            String group = reqJson.getString("group");

            List<LearnInfo> learnInfoList = learnInfoMapper.selectAll();
            if ("areaName".equals(group)){
                List<String> areaNameList = learnInfoList.stream().map(LearnInfo::getArea).distinct().filter(StrUtil::isNotBlank).collect(Collectors.toList());
                for (String area : areaNameList) {
                    JSONObject json = new JSONObject();
                    List<LearnInfo> collect = learnInfoList.stream().filter(LearnInfo -> LearnInfo.getArea() != null && LearnInfo.getArea().equals(area)).collect(Collectors.toList());
                    int field1 = collect.size();
                    long field2 = collect.stream().filter(learnInfo -> learnInfo.getStatus() != null && !learnInfo.getStatus().equals("1")).count();

                    json.put("areaName",area);
                    json.put("field1",field1);
                    json.put("field2", Convert.toInt(field2));
                    json.put("proportion",Convert.toInt(field1) == 0 ? "0.00%" : df.format((double) Convert.toInt(field2)  / Convert.toInt(field1)));
                    resList.add(json);
                }
            }else if ("department".equals(group)){
                List<String> departmentList = learnInfoList.stream().map(LearnInfo::getDepartment).distinct().filter(StrUtil::isNotBlank).collect(Collectors.toList());
                for (String department : departmentList) {
                    JSONObject json = new JSONObject();
                    List<LearnInfo> collect = learnInfoList.stream().filter(LearnInfo -> LearnInfo.getDepartment() != null && LearnInfo.getDepartment().equals(department)).collect(Collectors.toList());
                    int field1 = collect.size();
                    long field2 = collect.stream().filter(learnInfo -> learnInfo.getStatus() != null && !learnInfo.getStatus().equals("1")).count();

                    json.put("department",department);
                    json.put("field1",field1);
                    json.put("field2",Convert.toInt(field2));
                    json.put("proportion",Convert.toInt(field1) == 0 ? "0.00%" : df.format((double) Convert.toInt(field2)  / Convert.toInt(field1)));
                    resList.add(json);
                }
            }
            return WrapMapper.ok(resList);
        } catch (Exception e) {
            e.printStackTrace();
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper<Object> queryLearnFilePage(JSONObject reqJson) {
        try {
            DecimalFormat df = new DecimalFormat("0.00%");
            Integer pageSize = reqJson.getInteger("pageSize");
            Integer pageNum = reqJson.getInteger("pageNum");
            String department = reqJson.getString("department");
            PageHelper.startPage(pageNum, pageSize);

            LearnInfo queryLearnInfo = new LearnInfo();
            queryLearnInfo.setStatus("1");
            queryLearnInfo.setDepartment(department);
            List<LearnInfo> learnInfoList = learnInfoMapper.select(queryLearnInfo);
            List<BigInteger> annexIdList = learnInfoList.stream().map(LearnInfo::getAnnexId).distinct().collect(Collectors.toList());
            FileInfo queryFileInfo = new FileInfo();
            queryFileInfo.setIsDeleted("0");
            List<FileInfo> fileInfoList = fileInfoMapper.select(queryFileInfo);
            if (CollectionUtil.isNotEmpty(fileInfoList)){
                for (FileInfo fileInfo : fileInfoList) {
                    BigInteger id = fileInfo.getId();
                    if (annexIdList.contains(id)){
                        fileInfo.setIsLearn("1");
                    }else{
                        fileInfo.setIsLearn("0");
                    }
                }
            }

            Collections.sort(fileInfoList, Comparator.comparing(FileInfo::getId).reversed());
            return WrapMapper.ok(new PageInfo<>(fileInfoList));
        } catch (Exception e) {
            e.printStackTrace();
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper<Object> queryLearnFileGroupPage(JSONObject reqJson) {
        try {
            DecimalFormat df = new DecimalFormat("0.00%");
            List<Object> resList = CollectionUtil.newArrayList();
            String group = reqJson.getString("group");

            FileInfo queryFileInfo = new FileInfo();
            queryFileInfo.setIsDeleted("0");
            List<FileInfo> fileInfoList = fileInfoMapper.select(queryFileInfo);
            LearnInfo queryLearnInfo = new LearnInfo();
            queryLearnInfo.setStatus("1");
//            queryLearnInfo.setDepartment(department);
            List<LearnInfo> learnInfoList = learnInfoMapper.select(queryLearnInfo);
            if ("file".equals(group)){
                for (FileInfo fileInfo : fileInfoList) {
                    JSONObject json = new JSONObject();
                    BigInteger fileInfoId = fileInfo.getId();
                    String fileName = fileInfo.getFileName();
                    int field1 = fileInfoList.size();
                    long field2 = learnInfoList.stream()
                            .filter(learnInfo -> learnInfo.getAnnexId() != null && learnInfo.getAnnexId().equals(fileInfoId))
                            .filter(learnInfo -> learnInfo.getStatus() != null && learnInfo.getStatus().equals("1")).count();
                    json.put("fileName",fileName);
                    json.put("field1",field1);
                    json.put("field2", Convert.toInt(field2));
                    json.put("field3", Convert.toInt(field1-Convert.toInt(field2)));
                    json.put("proportion",Convert.toInt(field1) == 0 ? "0.00%" : df.format((double) Convert.toInt(field2)  / Convert.toInt(field1)));
                    resList.add(json);
                }
            }else if ("department".equals(group)){
                List<String> departmentList = learnInfoList.stream().map(LearnInfo::getDepartment).distinct().filter(StrUtil::isNotBlank).collect(Collectors.toList());
                for (String department : departmentList) {
                    JSONObject json = new JSONObject();
                    List<LearnInfo> collect = learnInfoList.stream().filter(LearnInfo -> LearnInfo.getDepartment() != null && LearnInfo.getDepartment().equals(department)).collect(Collectors.toList());
                    int field1 = collect.size();
                    long field2 = learnInfoList.stream()
                            .filter(learnInfo -> learnInfo.getStatus() != null && learnInfo.getStatus().equals("1")).count();
                    json.put("department",department);
                    json.put("field1",field1);
                    json.put("field2", Convert.toInt(field2));
                    json.put("field3", Convert.toInt(field1-Convert.toInt(field2)));
                    json.put("proportion",Convert.toInt(field1) == 0 ? "0.00%" : df.format((double) Convert.toInt(field2)  / Convert.toInt(field1)));
                    resList.add(json);
                }
            }
            return WrapMapper.ok(resList);
        } catch (Exception e) {
            e.printStackTrace();
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }
}
